package com.workManager.base;


import com.workManager.config.RespCode;
import com.workManager.exception.LoginException;
import com.workManager.pojo.TdUser;
import com.workManager.util.SecurityUtil;
import com.workManager.vo.CurrentUserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;

/**
 * 
* @ClassName: LoginHelper 
* @Description: 登录辅助类
* @author linz
* @date 2017年1月15日 上午12:16:18
*
 */
public final class LoginHelper {
	private LoginHelper() {
	}

	/** 用户登录 */
	public static final Boolean login(String account, String password) {
		UsernamePasswordToken token = new UsernamePasswordToken(account, password);
		token.setRememberMe(true);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return subject.isAuthenticated();
		}catch(UnknownAccountException e){

			throw new LoginException(RespCode.ACCOUNT_PASSWORD_ERROR,e);
		} catch (LockedAccountException e) {

			throw new LoginException(RespCode.paramFormat(RespCode.USER_LOCKED, token.getPrincipal()),e);
		} catch (DisabledAccountException e) {

			throw new LoginException(RespCode.paramFormat(RespCode.USER_INVALID, token.getPrincipal()),e);
		} catch (ExpiredCredentialsException e) {

			throw new LoginException(RespCode.paramFormat(RespCode.USER_INVALID, token.getPrincipal()),e);
		} catch (Exception e) {

			throw new LoginException(RespCode.LOGIN_FAIL,e);
		}
	}

//	/** 验证新旧密码 */
//	public  static  final Boolean  validatepassWrod(){
//
//		Subject subject = SecurityUtils.getSubject();
//
//
//
//		return  true;
//	}



	/**
	 * 
	* @Title: initCurrentUserVO 
	* @Description: 登陆时初始化 CurrentUserVO
	* @param @param user
	* @param @return 
	* @return CurrentUserVO
	* @author linz
	* @throws
	 */
	public static final CurrentUserVO initCurrentUserVO(TdUser user){
      //  SysRoleService sysRoleService = (SysRoleService) SpringContextHelper.getBean("sysRoleService");
      //  List<String> roleIds = sysRoleService.getUserRoleByUid(user.getId());
        CurrentUserVO vo = new CurrentUserVO();
		vo.setLoginCode(user.getLoginCode());
		vo.setUid(user.getUserId());
		vo.setUserName(user.getUserName());

        return vo;
	}

	/**
	 * 加密
	 */
	public String encryptPassword(String password) {
		return SecurityUtil.encryptMd5(SecurityUtil.encryptSHA(password));
	}
}
